package com.person.filter;

import com.alibaba.fastjson.JSONObject;
import com.person.common.BaseContext;
import com.person.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符写法
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        //强转类型
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse res=(HttpServletResponse) servletResponse;

        //获取请求中的url
        String requestURI = req.getRequestURI();
        log.info("请求路径{}",requestURI);
        //定义不需要拦截的路径
        String[] uris =new String[]{
//                "/employee/login",
//                "/employee/logout",
//                "/backend/**",
//                "/front/**"
                "/front/**",
                "/backend/**",
                "/static/**",
                "/",
                "/employee/login",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };

        //判断是否有为放行路径
        if (check(uris,requestURI)){
            log.info("放行该路径：{}",requestURI);
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //登录判断，存在员工sessionid，就登录
        if ((req.getSession().getAttribute("employee")) !=null ){
            Long empId = (Long) req.getSession().getAttribute("employee");
            //获取线程id，设置员工id
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //登录判断，存在用户sessionid，就登录
        if(req.getSession().getAttribute("user") !=null){
            Long userId = (Long) req.getSession().getAttribute("user");
            //获取线程id，设置用户id
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }



        //未登录，响应错误信息返回
        log.info("未登录");
        R<Object> result = R.error("NOTLOGIN");
        String jsonString = JSONObject.toJSONString(result);
        res.getWriter().write(jsonString);
        return;

    }

    //定义方法，判断路径是否为放行路径
    public boolean check(String[] uris,String requestUri){
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestUri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
